package com.act;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bean.Friend;
import com.bean.FriendList;
import com.common.Constant;
import com.common.LocalFileHelper;
import com.common.TextHttpResponseHandler;
import com.mUI.SideBar;
import com.mUI.SideBar.OnTouchingLetterChangedListener;
import com.mUI.XListView;
import com.mUI.XListView.IXListViewListener;
import com.xike.kyt.R;
import com.xike.util.CharacterParser;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class Mine_FriendAct extends BaseAct {

	private static final int REQUEST_CODE_TO_NEWFRIEND = 1;

	TextView tv_back;
	XListView listView;
	MyAdapter adapter;

	FriendList friendList;
	ArrayList<Friend> friends = new ArrayList<Friend>();

	PinyinComparator pinyinComparator;
	CharacterParser characterParser;

	private SideBar sideBar;
	private TextView dialog;

	boolean isRefresh = false;
	int pageCursor = 1;
	boolean isLoadingMore = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_friend_mine);
		pinyinComparator = new PinyinComparator();
		characterParser = CharacterParser.getInstance();
		initViews();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_NEWFRIEND && resultCode > 0) {
			serviceGetMineFriends();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void initViews() {

		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		tv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		sideBar = (SideBar) findViewById(R.id.friendMine_sidrbar);
		dialog = (TextView) findViewById(R.id.friendMine_tv_dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					listView.setSelection(position);
				}

			}
		});

		LinearLayout layout_newFriend = (LinearLayout) View.inflate(this, R.layout.layout_sortlistview_item, null);
		((TextView) layout_newFriend.findViewById(R.id.lvitem_sort_tv_name)).setText("新的朋友");
		((TextView) layout_newFriend.findViewById(R.id.lvitem_sort_tv_tag)).setVisibility(View.GONE);
		((ImageView) layout_newFriend.findViewById(R.id.lvitem_sort_img)).setImageResource(R.drawable.new_friend);

		listView = (XListView) findViewById(R.id.friendMine_listView);
		listView.setPullRefreshEnable(true);
		listView.setPullLoadEnable(true);
		listView.setAutoLoadEnable(true);

		listView.addHeaderView(layout_newFriend);

		adapter = new MyAdapter();
		listView.setAdapter(adapter);
		listView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pageCursor = 1;
				isRefresh = true;
				serviceGetMineFriends();
			}

			@Override
			public void onLoadMore() {
				pageCursor++;
				isLoadingMore = true;
				serviceGetMineFriends();
			}
		});

		// serviceTest();
		serviceGetMineFriends();

	}

	@Override
	protected void updateViews() {
		ArrayList<Friend> loadFriends = friendList.getFriends();
		initLoadDatas(loadFriends);
		if (loadFriends != null && loadFriends.size() > 0) {

			if (isRefresh) {
				friends.clear();
				friends.addAll(loadFriends);
				adapter.notifyDataSetChanged();
				isRefresh = false;
				listView.stopRefresh();
				listView.updateRefreshTime();
			} else {
				friends.addAll(loadFriends);
				adapter.notifyDataSetChanged();
				if (isLoadingMore) {
					listView.stopLoadMore();
				}
				if (friendList.getNext_cursor() > 0) {
					listView.showFooterView();
				} else {
					listView.setPullLoadEnable(false);
				}
			}

		}
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 1) {
					startActivityForResult(new Intent(Mine_FriendAct.this, Friend_NewAct.class), REQUEST_CODE_TO_NEWFRIEND);
				} else {
					Friend friend = friends.get(position - listView.getHeaderViewsCount());
					Intent it_chat = new Intent(Mine_FriendAct.this, ChatAct.class);
					it_chat.putExtra("userId", friend.getIm_name());
					it_chat.putExtra("userName", friend.getNick_name());
					startActivity(it_chat);
				}

			}
		});
	}

	private void serviceGetMineFriends() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("page_cursor", String.valueOf(pageCursor)));
		params.add(new BasicNameValuePair("page_count", String.valueOf(Constant.LIST_PAGESIZE)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_FRIEND_MINE, params);
		// 本地缓存
		if (LocalFileHelper.getInstance(this).fileIsExited(strUrl) && !isRefresh) {
			FriendList result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), FriendList.class);
			dealRequestResult(result);
			return;
		}

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				FriendList result = gson.fromJson(responseString, FriendList.class);
				dealRequestResult(result);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				if (isRefresh) {
					listView.stopRefresh();
				}
				mToast.showToast(Mine_FriendAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(FriendList result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				friendList = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
				if (isRefresh) {
					listView.stopRefresh();
				}
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
			if (isRefresh) {
				listView.stopRefresh();
			}
		}
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return friends.size();
		}

		@Override
		public Friend getItem(int position) {
			return friends.get(position);
		}

		@Override
		public long getItemId(int position) {
			return friends.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			Friend friend = getItem(position);
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(Mine_FriendAct.this).inflate(R.layout.layout_sortlistview_item, null);
				viewHolder.tv_name = (TextView) convertView.findViewById(R.id.lvitem_sort_tv_name);
				viewHolder.tv_tag = (TextView) convertView.findViewById(R.id.lvitem_sort_tv_tag);
				viewHolder.img = (ImageView) convertView.findViewById(R.id.lvitem_sort_img);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			// 根据position获取分类的首字母的Char ascii值
			int section = getSectionForPosition(position);

			// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
			if (position == getPositionForSection(section)) {
				viewHolder.tv_tag.setVisibility(View.VISIBLE);
				viewHolder.tv_tag.setText(friend.getFirstChar());
			} else {
				viewHolder.tv_tag.setVisibility(View.GONE);
			}

			MyUtil.setTextViewText(viewHolder.tv_name, friend.getNick_name(), 0, "未知用户");
			BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
			MyUtil.displayImageView(Mine_FriendAct.this, friend.getAvator(), viewHolder.img, bd.getBitmap(), false);

			return convertView;
		}

		class ViewHolder {
			TextView tv_tag;
			TextView tv_name;
			ImageView img;
		}

		/**
		 * 根据ListView的当前位置获取分类的首字母的Char ascii值
		 */
		public int getSectionForPosition(int position) {
			return friends.get(position).getFirstChar().charAt(0);
		}

		/**
		 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < friends.size(); i++) {
				String sortStr = friends.get(i).getFirstChar();
				char firstChar = sortStr.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}

			return -1;
		}
	}

	private void initLoadDatas(ArrayList<Friend> loadFriends) {
		for (Friend friend : loadFriends) {
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(StringUtil.isNotNull(friend.getNick_name()) ? friend.getNick_name() : "未知用户");
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				friend.setFirstChar(sortString.toUpperCase());
			} else {
				friend.setFirstChar("#");
			}
		}
		// 根据a-z进行排序
		Collections.sort(loadFriends, pinyinComparator);
	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr, ArrayList<Friend> loadFriends) {

		if (TextUtils.isEmpty(filterStr)) {
			friends = loadFriends;
		} else {
			friends.clear();
			for (Friend friend : loadFriends) {
				String name = friend.getNick_name();
				if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
					friends.add(friend);
				}
			}
		}
		adapter.notifyDataSetChanged();
	}

	class PinyinComparator implements Comparator<Friend> {

		public int compare(Friend o1, Friend o2) {
			if (o1.getFirstChar().equals("@") || o2.getFirstChar().equals("#")) {
				return -1;
			} else if (o1.getFirstChar().equals("#") || o2.getFirstChar().equals("@")) {
				return 1;
			} else {
				return o1.getFirstChar().compareTo(o2.getFirstChar());
			}
		}

	}

}
